<?php
/**
 * ToolsUserIdentity represents the data needed to identity a user.
 * 
 * Yawii 版权所有 @ 2012
 */
class ToolsUserIdentity extends CUserIdentity
{
	const ERROR_LOCKED = 4;	// account is locked
	const ERROR_EXPIRED = 5;// account is expired
	
	// Need to store the user's ID:
	private $_id;
	public function getId() {
		return $this->_id;
	}
	public function setId($id) {
		$this->_id = $id;
	}

	/**
	 * Authenticates a user with database.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		//query sys_admin_acount
		$sql_admin = 'SELECT id, email, password, name, sys_role, status FROM tbl_sys_admin_account WHERE email=:email ';
		// fetch password and username
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_admin);
		$row = $command->queryRow(true, array('email' => $this->username));
		if (empty($row)) {
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		} else {
			//DB password not hash
			$pasword_in_db = $this->password;
			if ($row['password'] === $pasword_in_db) {
				switch($row['status']) {
					case self::ERROR_LOCKED:
					case self::ERROR_EXPIRED:
						$this->errorCode = $row['status'];
						break;
					default:
						$this->errorCode = self::ERROR_NONE;
						$this->_id = $row['id'];
						$this->setState('email', $this->username);
						$this->setState('name', $row['name']);
						$this->setState('sys_role', $row['sys_role']);
						$this->setState('status', $row['status']);
						//update the login time
						$sql_login = 'UPDATE tbl_sys_admin_account SET login_time=NOW() WHERE id=:id';
						$connection = Yii::app()->db;
						$command = $connection->createCommand($sql_login);
						$command->execute(array(':id'=>$this->_id));
						break;
				}
			} else {
				$this->errorCode = self::ERROR_PASSWORD_INVALID;
			}
		}
		$connection->active = false;
		
		return (self::ERROR_NONE == $this->errorCode);
	}
}